import React, { useEffect, useState } from "react";
import { Space, Table, Button, message, Input, Modal, Form } from "antd";
import type { TableProps } from "antd";
import http from "../../utils/http";
// 类型
interface DataType {
  key: React.Key;
  doctorid: string;
  doctorimage: string;
  doctorname: string;
  doctoradministre: string;
  doctoriddoc: string;
  doctorcity: string;
}

const Index: React.FC = () => {
  // 数据
  const [datalist, setDatalist] = useState([]);
  const [originalDatalist, setOriginalDatalist] = useState<DataType[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const { Search } = Input;
  // 分页
  const [pageCode, setPageCode] = useState(1);
  const [pageSize, setPageSize] = useState(500);
  const [searchValue, setSearchValue] = useState("");
  const columns: TableProps<DataType>["columns"] = [
    {
      title: (
        <div>
          <Button
            disabled={selectedRowKeys.length === 0}
            type="primary"
            style={{ marginRight: "10px" }}
          >
            批量删除
          </Button>
          ID
        </div>
      ),
      align: "center",
      dataIndex: "doctorid",
      key: "doctorid",
    },
    {
      title: "头像",
      align: "center",
      dataIndex: "doctorimage",
      key: "doctorimage",
      render: (text, record) => {
        return (
          <img
            src={text}
            alt={record.doctorimage}
            style={{ width: "80px", height: "80px" }}
          />
        );
      },
    },
    {
      title: "名字",
      align: "center",
      dataIndex: "doctorname",
      key: "doctorname",
    },
    {
      title: "科室",
      align: "center",
      dataIndex: "doctoradministre",
      key: "doctoradministre",
    },
    {
      title: "电话",
      align: "center",
      dataIndex: "doctoriddoc",
      key: "doctoriddoc",
    },
    {
      title: "地址",
      align: "center",
      dataIndex: "doctorcity",
      key: "doctorcity",
    },
    {
      title: "Action",
      align: "center",
      key: "doctorid",
      render: (record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => EditshowModal(record)}>
            编辑
          </Button>
          <Button type="primary" danger onClick={() => hanDel(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 渲染数据
  const FearchList = async () => {
    const res = await http.get("/doctor/list", {
      params: {
        pageCode,
        pageSize,
      },
    });
    const { code, data } = res.data;
    console.log(res.data);
    if (code === 20000) {
      setDatalist(data);
      setOriginalDatalist(data);
    }
  };
  useEffect(() => {
    FearchList();
  }, []);
  // 删除数据
  const hanDel = async (record: DataType) => {
    const updatedDataList = datalist.filter(
      (item: DataType) => item.doctorid !== record.doctorid
    );
    setDatalist(updatedDataList);
    message.success("删除成功");
  };
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [DialogState, setDialogState] = useState(true);
  const [editedRecord, setEditedRecord] = useState<DataType | null>(null);
  // 编辑/添加
  const AddshowModal = () => {
    form.resetFields();
    setIsModalOpen(true);
    setDialogState(true);
    setEditedRecord(null);
  };
  const EditshowModal = (record: DataType) => {
    form.setFieldsValue(record);
    setIsModalOpen(true);
    setDialogState(false);
    setEditedRecord(record);
  };

  const handleOk = async () => {
    const formData = form.getFieldsValue();
    if (DialogState) {
      // 添加
      const newId = (datalist.length + 1).toString();
      const newRecord: DataType = {
        key: newId,
        doctorid: newId,
        doctorimage: formData.doctorimage,
        doctorname: formData.doctorname,
        doctoradministre: formData.doctoradministre,
        doctoriddoc: formData.doctoriddoc,
        doctorcity: formData.doctorcity,
      };
      setDatalist([newRecord, ...datalist]);
      message.success("添加成功");
    } else {
      // 编辑
      const updatedDataList = datalist.map((item: DataType) =>
        item.doctorid === editedRecord.doctorid
          ? {
              ...item,
              doctorimage: formData.doctorimage,
              doctorname: formData.doctorname,
              doctoradministre: formData.doctoradministre,
              doctoriddoc: formData.doctoriddoc,
              doctorcity: formData.doctorcity,
            }
          : item
      );
      setDatalist(updatedDataList);
      message.success("编辑成功");
    }
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // 查询
  const onSearch = (value: string) => {
    setSearchValue(value);
    if (!value) {
      setDatalist(originalDatalist);
    } else {
      const filteredData = originalDatalist.filter((item) =>
        Object.values(item).some((v) =>
          String(v).toLowerCase().includes(value.toLowerCase())
        )
      );
      setDatalist(filteredData);
    }
  };
  return (
    <div>
      <div>
        <Button
          type="primary"
          style={{ marginRight: "60px" }}
          onClick={() => AddshowModal()}
        >
          增加数据
        </Button>
        <Search
          placeholder="请输入搜索内容"
          allowClear
          enterButton="Search"
          size="large"
          style={{ width: "300px" }}
          onSearch={onSearch}
        />
      </div>

      <Table<DataType>
        rowKey={"doctorid"}
        rowSelection={{
          onChange(newSelectedRowKeys: React.Key[]) {
            console.log(newSelectedRowKeys);
            setSelectedRowKeys(newSelectedRowKeys);
          },
        }}
        columns={columns}
        dataSource={datalist}
      />
      {/* 添加编辑和增加弹框 */}
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} name="control-hooks" style={{ maxWidth: 600 }}>
          <Form.Item name="doctorid" label="ID" rules={[{ required: true }]}>
            <Input disabled />
          </Form.Item>
          <Form.Item
            name="doctorimage"
            label="头像"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="doctorname"
            label="名字"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="doctoradministre"
            label="科室"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="doctoriddoc"
            label="电话"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="doctorcity"
            label="地区"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Index;
